package com.lzc.zhxy.controller;

import com.lzc.zhxy.pojo.LoginForm;
import com.lzc.zhxy.pojo.TbAdmin;
import com.lzc.zhxy.pojo.TbStudent;
import com.lzc.zhxy.pojo.TbTeacher;
import com.lzc.zhxy.service.TbAdminService;
import com.lzc.zhxy.service.TbStudentService;
import com.lzc.zhxy.service.TbTeacherService;
import com.lzc.zhxy.util.CreateVerifiCodeImage;
import com.lzc.zhxy.util.JwtHelper;
import com.lzc.zhxy.util.Result;
import com.lzc.zhxy.util.ResultCodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Api(tags = "系统控制器")
@RestController
@RequestMapping("/sms/system")
public class SystemController {

    @Autowired
    private TbAdminService tbAdminService;
    @Autowired
    private TbTeacherService tbTeacherService;
    @Autowired
    private TbStudentService tbStudentService;

    @ApiOperation("获取验证码图片")
    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response) {
        /**
         * 1、获取图片
         * 2、获取图片验证码
         * 3、将图片验证码文本放入session域为下一次验证做准备
         * 4、将验证码图片响应给浏览器
         */
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode());
        request.getSession().setAttribute("verifiCode", verifiCode);
        try {
            ImageIO.write(verifiCodeImage, "JPEG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm, HttpServletRequest request) {
        //验证码是否有效
        HttpSession session = request.getSession();
        String systemVerifiCode =(String) session.getAttribute("verifiCode");
        String loginVerifiCode = loginForm.getVerifiCode();
        if("".equals(systemVerifiCode)){
            // session过期,验证码超时,
            return Result.fail().message("验证码失效,请刷新后重试");
        }
        if (!loginVerifiCode.equalsIgnoreCase(systemVerifiCode)){
            // 验证码有误
            return Result.fail().message("验证码有误,请刷新后重新输入");
        }
        //从session中移除验证码
        session.removeAttribute("verifiCode");
        //分用户类型进行校验
        //准备一个map用来存放响应数据
        HashMap<String, Object> map = new HashMap<>();
        switch (loginForm.getUserType()) {
            case "1":
                try {
                    //管理员登录
                    TbAdmin admin = tbAdminService.login(loginForm);
                    if (admin != null) {
                        //用户类型和用户id转换成一个密文，以token的形式返回给客户端
                        String token = JwtHelper.createToken(admin.getId().longValue(), 1);
                        map.put("token", token);
                    } else {
                        throw new RuntimeException("登录失败");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

            case "2":
                //学生登录
                TbStudent student = tbStudentService.login(loginForm);
                try {
                    if (student != null) {
                        //用户类型和用户id转换成一个密文，以token的形式返回给客户端
                        String token = JwtHelper.createToken(student.getId().longValue(), 2);
                        map.put("token", token);
                    } else {
                        throw new RuntimeException("登录失败");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

            case "3":
                //教师登录
                TbTeacher teacher = tbTeacherService.login(loginForm);
                try {
                    if (teacher != null) {
                        //用户类型和用户id转换成一个密文，以token的形式返回给客户端
                        String token = JwtHelper.createToken(teacher.getId().longValue(), 3);
                        map.put("token", token);
                    } else {
                        throw new RuntimeException("登录失败");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

        }
        return Result.fail().message("无此用户");

    }


    @ApiOperation("通过token获取用户信息")
    @GetMapping("/getInfo")
    public Result getUserInfoByToken(HttpServletRequest request, @RequestHeader("token")String token){
        /**
         * 获取用户Token信息
         * 检查token是否过期
         */
        boolean isEx = JwtHelper.isExpiration(token);
        if (isEx){
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        /**
         * 解析Token
         */
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);

        /**
         * 根据用户类型返回用户信息
         */
        // 准备一个Map集合用于存响应的数据
        Map<String,Object> map=new HashMap<>();
        switch (userType){
            case 1:
                TbAdmin admin = tbAdminService.getAdminById(userId.intValue());
                map.put("user",admin);
                map.put("userType",1);
                break;
            case 2:
                TbStudent student = tbStudentService.getStudentById(userId.intValue());
                map.put("user",student);
                map.put("userType",2);
                break;
            case 3:
                TbTeacher teacher = tbTeacherService.getTeacherById(userId.intValue());
                map.put("user",teacher);
                map.put("userType",3);
                break;
        }
        return  Result.ok(map);

    }

    @ApiOperation("头像上传统一入口")
    @PostMapping("/headerImgUpload")
    public Result headerImgUpload(
            @ApiParam("文件二进制数据") @RequestPart("multipartFile") MultipartFile multipartFile
    ){
        //使用UUID随机生成文件名
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        //生成新的文件名
        String filename = uuid.concat(multipartFile.getOriginalFilename());
        //生成文件的保存路径(实际生产环境这里会使用真正的文件存储服务器)
        /**
         * 注意此处路径应选择缓存文件存储路径
         */
        String portraitPath ="D:/git/zhxy/target/classes/public/upload/".concat(filename);
        //保存文件
        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String headerImg ="upload/"+filename;
        return Result.ok(headerImg);


    }
}
